# -*- coding: utf-8 -*-
# @Time    : 2019/10/21 15:11
# @Author  : ZSQ
# @Email   : zsq199170918@163.com
# @FileName: baoding_mongo_merge.py
# @Software: PyCharm
HOST = '192.168.1.159'
PORT = 27017

from pymongo import MongoClient


class BaoDing(object):
    def __init__(self, host, port):
        self.client = MongoClient(host=host, port=port, )

    def format_estate(self, db, col1, col2, clo3, query=None, skip_num=0, limit_num=1000):
        clo1 = self.client[db][col1]
        clo2 = self.client[db][col2]
        clo3 = self.client[db][clo3]
        while True:
            item_li = list(clo1.find(query).skip(skip_num).limit(limit_num))
            if len(item_li):
                skip_num += 1000
                for item in item_li:
                    del item['_id']
                    query_p = dict(
                        projectName=item['projectName'],
                        developerName=item['developerName'],
                    )
                    item_p_Li = list(clo2.find(query_p))

                    if len(item_p_Li):
                        for item_p in item_p_Li:
                            item['preSalePermit'] = item_p['preSalePermit']
                            item['certDate'] = item_p['certDate']
                            # item['preSaleBuilding'] = item_p['preSaleBuilding']
                            # item['preSaleArea'] = item_p['preSaleArea']
                            # item['preSaleRoomNo'] = item_p['preSaleRoomNo']
                            filter_dict = dict(
                                projectName=item['projectName'],
                                developerName=item['developerName'],
                                preSalePermit=item['preSalePermit'],
                                certDate=item['certDate'],
                            )
                            clo3.update_one(filter_dict, {'$set': item}, upsert=True)
                    else:
                        item['preSalePermit'] = None
                        item['certDate'] = None
                        filter_dict = dict(
                            projectName=item['projectName'],
                            developerName=item['developerName'],
                            preSalePermit=item['preSalePermit'],
                            certDate=item['certDate'],
                        )
                        clo3.update_one(filter_dict, {'$set': item}, upsert=True)
            else:
                break


if __name__ == '__main__':
    bd = BaoDing(HOST, PORT)
    bd.format_estate('zsq_bdfc', 'estate', 'permit', 'estate_permit')
